package usercontroller

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"vpn-management-server/logger"
	"vpn-management-server/network"
	"vpn-management-server/src/model/usermodel"
)

func handleSimAuthCallback(w http.ResponseWriter, r *http.Request) {
	// 确保只处理POST请求
	if r.Method != http.MethodPost {
		logger.Logger.Error("Invalid request method: ", r.Method)
		http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
		return
	}

	// 读取请求体
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Error reading request body", http.StatusInternalServerError)
		return
	}
	defer r.Body.Close()
	fmt.Println(string(body))

	// 解析JSON数据
	var requestData usermodel.SimCallBackRequest
	err = json.Unmarshal(body, &requestData)
	if err != nil {
		http.Error(w, "Invalid JSON format", http.StatusBadRequest)
		return
	}

	var netRequest network.NetRequest
	var netResponse network.NetResponse

	netRequest.SetModel(&requestData)

	logger.Logger.Info("Calling SimAuthStatus")
	SimAuthCallback(context.Background(), &netRequest, &netResponse)

	// 将 NetResponse 写回到 HTTP 响应中
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(netResponse.Code) // 使用 netResponse.Code 作为 HTTP 状态码
	json.NewEncoder(w).Encode(netResponse.Data)
}

func StartHandleSimAuthCallback() {
	http.HandleFunc("/SimAuthCallBack", handleSimAuthCallback)
	logger.Logger.Info("HandleSimAuthCallback Server Starting")
	err := http.ListenAndServe(":80", nil)
	if err != nil {
		logger.Logger.Error("Failed to start server:", err)
		return
	}
}
